package cn.hg.solon.youcan.system.provider;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.db.PageResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;

import com.easy.query.api4j.client.EasyQuery;
import com.easy.query.api4j.select.Queryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.solon.annotation.Db;

import cn.hg.solon.youcan.common.constant.WebConstants;
import cn.hg.solon.youcan.system.entity.EqOperateLog;
import cn.hg.solon.youcan.system.entity.OperateLog;
import cn.hg.solon.youcan.system.service.OperateLogService;

/**
 * @author 胡高
 */
@Component
public class EqOperateLogProvider implements OperateLogService {

    @Db("db1")
    private EasyQuery easyQuery;

    private Queryable<EqOperateLog> buildQuery(Map<String, Object> map) {
        String type = (String)map.get("type");
        String method = (String)map.get("method");
        String status = (String)map.get("status");
        String word = (String)map.get("word");
        Date startDate = (Date)map.get("startDate");
        Date endDate = (Date)map.get("endDate");
        String sortField = (String)map.get("sortField");
        String sortType = (String)map.get("sortType");

        boolean customOrder = StrValidator.isNotBlank(sortField) && StrValidator.isNotBlank(sortType);

        // FROM sys_operate_log AS t
        return this.easyQuery.queryable(EqOperateLog.class)
            // WHERE t.`type` = ${type} AND t.`status` = ${status}
            //      AND ${startDate} <= t.`action_datetime` AND t.`action_datetime` <= ${endDate}
            .where(w -> w.eq(StrValidator.isNotBlank(type), EqOperateLog::getType, type)
                .eq(StrValidator.isNotBlank(method), EqOperateLog::getMethod, method)
                .eq(StrValidator.isNotBlank(status), EqOperateLog::getStatus, status)
                .rangeClosed(ObjUtil.isNull(startDate) || ObjUtil.isNull(endDate), EqOperateLog::getActionDatetime,
                    ObjUtil.isNotNull(startDate), startDate, ObjUtil.isNotNull(endDate), endDate)
                //  AND (t1.`title` LIKE '%${word}%' OR t1.`user_name` LIKE '%${word}%' OR t1.`dept_name` LIKE '%${word}%'
                //       OR t1.`url` LIKE '%${word}%' OR t1.`ip` LIKE '%${word}%' OR t1.`location` LIKE '%${word}%'
                //       OR t1.`param` LIKE '%${word}%' OR t1.`result` LIKE '%${word}%' OR t1.`message` LIKE '%${word}%')
                .and(StrValidator.isNotBlank(word),
                    a -> a.like(EqOperateLog::getTitle, word)
                    .or().like(EqOperateLog::getUserName, word)
                    .or().like(EqOperateLog::getDeptName, word)
                    .or().like(EqOperateLog::getUrl, word)
                    .or().like(EqOperateLog::getIp, word)
                    .or().like(EqOperateLog::getLocation, word)
                    .or().like(EqOperateLog::getParam, word)
                    .or().like(EqOperateLog::getResult, word)
                    .or().like(EqOperateLog::getMessage, word)
                    ))
            // ORDER BY ${sortField} DESC
            .orderBy(customOrder, ob -> ob.sqlNativeSegment(CharSequenceUtil.toUnderlineCase(sortField)),
                !CharSequenceUtil.equalsIgnoreCase(sortType, WebConstants.ORDER_DIRECTION_DESC));
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.OperateLogService#clear()
     */
    @Tran
    @Override
    public boolean clear() {
        return this.easyQuery.deletable(EqOperateLog.class).allowDeleteStatement(true).executeRows() > 0L;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.OperateLogService#delete(java.util.List)
     */
    @Tran
    @Override
    public boolean delete(List<Integer> idList) {
        return this.easyQuery.deletable(EqOperateLog.class)
            .where(w -> w.in(EqOperateLog::getId, idList))
            .executeRows() > 0;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.OperateLogService#get(java.lang.Integer)
     */
    @Override
    public OperateLog get(Integer id) {
        return this.easyQuery.queryable(EqOperateLog.class).whereById(id).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.OperateLogService#insert(cn.hg.solon.youcan.system.entity.OperateLog)
     */
    @Tran
    @Override
    public boolean insert(OperateLog bean) {
        EqOperateLog cloneBean = BeanUtil.copyProperties(bean, EqOperateLog.class);

        return this.easyQuery.insertable(cloneBean).executeRows() > 0;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.OperateLogService#pageBy(int, int, java.util.Map)
     */
    @Override
    public PageResult<? extends OperateLog> pageBy(int pageNumber, int pageSize, Map<String, Object> paraMap) {
        EasyPageResult<EqOperateLog> pageList = this.buildQuery(paraMap).toPageResult(Convert.toLong(pageNumber), pageSize);

        PageResult<EqOperateLog> result = new PageResult<>();
        result.addAll(pageList.getData());
        result.setTotal(Convert.toInt(pageList.getTotal()));

        return result;
    }

}
